/**
 * Copyright (c) 2017-2020 四川智慧云天 All rights reserved.
 *
 * https://www.sczhyt.cn
 *
 * 版权所有，侵权必究！
 */

package cn.sczhyt.modules.sys.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.sczhyt.common.utils.R;
import cn.sczhyt.modules.sys.dao.*;
import cn.sczhyt.modules.sys.entity.*;
import cn.sczhyt.modules.sys.oauth2.TokenGenerator;
import cn.sczhyt.modules.sys.service.SysUserTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;


@Service("sysUserTokenService")
public class SysUserTokenServiceImpl extends ServiceImpl<SysUserTokenDao, SysUserTokenEntity> implements SysUserTokenService {
	//12小时后过期
	private final static int EXPIRE = 3600 * 12;

	@Autowired
	private SysUserRoleDao userRoleDao;
	@Autowired
	private SysUserInfoDao userInfoDao;
	@Autowired
	private SysOrganizeInfoDao organizeInfoDao;
	@Autowired
	private SysUserDao userDao;

	@Override
	public R createToken(String userId) {
		//生成一个token
		String token = TokenGenerator.generateValue();

		//当前时间
		Date now = new Date();
		//过期时间
		Date expireTime = new Date(now.getTime() + EXPIRE * 100000);

		//判断是否生成过token
		SysUserTokenEntity tokenEntity = this.getById(userId);
		if(tokenEntity == null){
			tokenEntity = new SysUserTokenEntity();
			tokenEntity.setUserId(userId);
			tokenEntity.setToken(token);
			tokenEntity.setUpdateTime(now);
			tokenEntity.setExpireTime(expireTime);

			//保存token
			this.save(tokenEntity);
		}else{
			tokenEntity.setToken(token);
			tokenEntity.setUpdateTime(now);
			tokenEntity.setExpireTime(expireTime);

			//更新token
			this.updateById(tokenEntity);
		}
		//查询角色
		SysUserRoleEntity userRoleEntity = userRoleDao.selectByUserId(userId);

		//超级管理无角色，需要判断是否为空
		if (userRoleEntity == null){

			return R.ok().put("roleId",null).put("token", token).put("expire", EXPIRE).put("data",userId);
		}
		String roleId = userRoleEntity.getRoleId();
		//判断是否为委员角色
		if (userRoleEntity.getRoleId().equals("1")) {

			SysUserInfoEntity data = userInfoDao.selectByUserId(userId);
			SysUserEntity userEntity = userDao.selectById(userId);
			return R.ok().put("roleId",roleId).put("token", token).put("expire", EXPIRE).put("data",data).put("user",userEntity);
		}

		SysOrganizeInfoEntity data = organizeInfoDao.selectByUserId(userId);
		SysUserEntity userEntity = userDao.selectById(userId);

		return R.ok().put("roleId",roleId).put("token", token).put("expire", EXPIRE).put("data",data).put("user",userEntity);
	}

	@Override
	public void logout(String userId) {
		//生成一个token
		String token = TokenGenerator.generateValue();

		//修改token
		SysUserTokenEntity tokenEntity = new SysUserTokenEntity();
		tokenEntity.setUserId(userId);
		tokenEntity.setToken(token);
		this.updateById(tokenEntity);
	}
}
